package com.hbu.housingbrokerug.activities;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Gallery;
import android.widget.ListView;

import com.fedorvlasov.lazylist.LazyAdapterCategoryType;
import com.hbu.housingbrokeruganda.Parser.JSONParser;
import com.hub.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * @author Lubwama Samuel(lubwamasamuel3[at]gmail[dot]com)
 */
@SuppressWarnings("deprecation")
public class Category extends Activity {
	private ProgressDialog pDialog;
	ListView list;
	Gallery gallery;
	LazyAdapterCategoryType adapter;
	String result = "";
	int arraysize;
	JSONParser jParser = new JSONParser();
	protected ImageLoader imageLoader = ImageLoader.getInstance();


	parserFromUrl parser = new parserFromUrl();

	public String[][] CategoryData;

	DisplayImageOptions options = parser.getOptions();
	public String ipOrDomain = parser.getIpOrDomain();

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.category_unit);
	 Bundle bundle=getIntent().getExtras();

		CategoryData = new String[][] {};
		
		new getAllHousingUnitInformation(bundle.getString("CATEGORY_TYPE"))
				.execute();
		

	}

	public void onDestroy() {
		try {
			list.setAdapter(null);
		} catch (Exception e) {

		}
		super.onDestroy();
	}

	private void getUnitsForCategory(int position) {

		Intent intent = new Intent(getApplicationContext(), Main.class);
		intent.putExtra("CATEGORY_ID", CategoryData[position][0]);
		intent.putExtra("CATEGORY_NAME", CategoryData[position][2]);
		startActivityForResult(intent, 100);

	}

	public class getAllHousingUnitInformation extends
			AsyncTask<String, String, String> {

		String categoryType1 = "";

		public getAllHousingUnitInformation(String categoryType) {

			categoryType1 = categoryType;

		}

		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(Category.this);
			pDialog.setMessage("Loading Houses From Server. Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected String doInBackground(String... params) {
			final String TAG_SUCCESS = "success";
			final String HOUSING_UNIT = "category";

			JSONObject json = jParser
					.makeHttpRequest((parser.getIpOrDomain() + parser
							.getQueryFileCategory()).toString(), "GET", parser
							.getParametersGetGategoryType(categoryType1));
			Log.d("PARAMERER NAME", params.toString());
			try {
				int success = json.getInt(TAG_SUCCESS);
				if (success == 1) {
					JSONArray jArray = json.getJSONArray(HOUSING_UNIT);
					CategoryData = new String[jArray.length()][13];
					for (int i = 0; i < jArray.length(); i++) {
						JSONObject json1 = jArray.getJSONObject(i);
						/* 1 */CategoryData[i][0] = json1
								.getString("category_id");
						/* 2 */CategoryData[i][1] = parser.getIpOrDomain()
								+ json1.getString("category_image");
						/* 3 */CategoryData[i][2] = json1
								.getString("category_name");					
						Log.d("Gallery",CategoryData[i][1]);
					}

				} else if (success == 0) {
					CategoryData = new String[1][1];
					CategoryData[0][0] = "No Data";
				} else if (success == 3) {

					CategoryData = new String[1][1];
					CategoryData[0][0] = "No Results";
				}
			} catch (Exception e) {
				Log.e("FAILED TO PASS DATA", e.toString());

			}
			return null;
		}

		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					/**
					 * Updating parsed JSON data into ListView
					 * */
					Log.d("DATA TRIAL", String.valueOf(CategoryData.length));
					if (CategoryData[0][0] != "No Data"
							&& CategoryData[0][0] != "No Results") {
						list = (ListView) findViewById(R.id.listCategoryById);
						adapter = new LazyAdapterCategoryType(Category.this, CategoryData,
								ipOrDomain);
						list.setAdapter(adapter);
						list.setItemsCanFocus(true);
						list.setOnItemClickListener(new OnItemClickListener() {

							@Override
							public void onItemClick(AdapterView<?> parent,
									View view, int position, long id) {
								getUnitsForCategory(position);
							}
						});
//						gallery = (Gallery) findViewById(R.id.gallery1);
//						gallery.setAdapter(new ImageGalleryAdapter());
//						gallery.setOnItemClickListener(new OnItemClickListener() {
//							@Override
//							public void onItemClick(AdapterView<?> parent,
//									View view, int position, long id) {
//								startingSingleUnit(position);
//							}
//						});
					} else {

						if (CategoryData[0][0] == "No Data") {
							AlertDialog alert = new AlertDialog.Builder(
									Category.this).create();
							alert.setTitle("Internet Reach Faluire Error");
							alert.setMessage("Failed To Connect To Server Check Your Internet Setting or Check If You have Data");
							alert.setButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											// closing the application
											finish();
										}
									});
							alert.show();
						} else if (CategoryData[0][0] == "No Results") {
							AlertDialog alert = new AlertDialog.Builder(
									Category.this).create();
							alert.setTitle("We are Embaraced");
							alert.setMessage("No housing Units Available \n Try Again Later");
							alert.setButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											finish();
										}
									});
							alert.show();

						}
					}
				}
			});
		}
	}
}